/*
 * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
 * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
 */
package com.yxw.live_vod_boot.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.obs.services.ObsClient;
import com.obs.services.model.PutObjectResult;
import com.yxw.live_vod_boot.entity.YxLiveShopUserEntity;
import com.yxw.live_vod_boot.entity.YxLiveAddressEntity;
import com.yxw.live_vod_boot.entity.YxSysUserEntity;
import com.yxw.live_vod_boot.utils.HuaWeiObsUtil;
import com.yxw.live_vod_boot.utils.RedisManager;
import com.yxw.live_vod_boot.vo.UserTokenVo;
import com.yxw.live_vod_facade.constant.LiveShopConstant;
import com.yxw.live_vod_facade.dto.LiveShopAddApplyDTO;
import com.yxw.live_vod_facade.vo.LivePushStreamRedisCacheVO;
import com.yxw.yxnet_cd_center.common.constant.CommonConstant;
import com.yxw.yxnet_cd_center.common.enums.FileClassifyEnum;
import com.yxw.yxnet_cd_center.common.exception.BaseException;
import com.yxw.yxnet_cd_center.common.utils.BaseDateTime;
import com.yxw.yxnet_cd_center.common.utils.BaseResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotBlank;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.net.URLEncoder;
import com.yxw.live_vod_boot.mapper.YxLiveShopUserMapper;
import com.yxw.live_vod_boot.mapper.YxLiveAddressMapper;
import com.yxw.live_vod_boot.mapper.UserMapper;
import com.yxw.live_vod_boot.utils.JwtUtil;
import com.yxw.live_vod_boot.vo.LoginUserVo;
import com.yxw.live_vod_boot.vo.UserInfoVo;
import com.yxw.yxnet_cd_center.common.constant.RedisIdConstant;
import com.yxw.yxnet_cd_center.common.utils.PasswordUtil;
import com.yxw.live_vod_boot.cache.QueueCache;
import com.yxw.live_vod_boot.vo.CheckLiveIsActiveVO;
import java.util.LinkedHashMap;
import java.util.concurrent.DelayQueue;
import org.apache.commons.lang3.StringUtils;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.yxw.yxnet_cd_center.common.result.TokenInfo;
import java.util.Map;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSON;
/**
 * 测试
 * @author hjx
 * @date 2023-11-23
 * @update 2023/12/4 17:31:17
 */
@Slf4j
@Api(value = "测试相关的操作", tags = {"测试相关的操作"})
@RestController
@RequestMapping("/api/live/test")
public class TestController {
    
    @Autowired
    private HuaWeiObsUtil huaWeiObsUtil;
    
    @Autowired
    private YxLiveShopUserMapper oYxLiveShopUserMapper;
    @Autowired
    private YxLiveAddressMapper oYxLiveAddressMapper;
    @Autowired
    private UserMapper userMapper;
    @Resource
    private RedisManager oRedisManager; 
    /*** 
    * 测试 redis Set Test
    * @param id
    * @param oYxLiveAppealDTO
    * @return BaseResult
    **/
    @ApiOperation(value ="测试",notes = "此接口用于各种测试")
    @ApiResponses({@ApiResponse(code = 200,message = "OK",response = BaseResult.class),})
    @PostMapping("/test")
    public BaseResult test()
    {  
        //return BaseResult.success(QueueCache.getCheckLiveIsActiveDelayQueue().size());
        /*
        String id = "YXW_LIVEVOD:LIVE:DELAYJOB_HASHMAP_5733d7a49ce867a5b9c9916f43e46500";
        DelayQueue<CheckLiveIsActiveVO> checkLiveIsActiveDelayQueue = new DelayQueue();
        oRedisManager.getMap(id);
        LinkedHashMap oDelayHashMap = (LinkedHashMap)oRedisManager.getMap(id);
        if(!oDelayHashMap.isEmpty())
        {            
            checkLiveIsActiveDelayQueue.addAll(oDelayHashMap.values());
        }
        */
        
        Long remoteTimeStamp = BaseDateTime.getDifferentAverageForBaidu();
        return BaseResult.success("remoteTimeStamp = " + remoteTimeStamp);
       
    }     
    /*** 
    * 测试 redis Set Test
    * @param id
    * @param oYxLiveAppealDTO
    * @return BaseResult
    **/
    @ApiOperation(value ="测试redisSetTest",notes = "此接口用于redis Set Test测试")
    @ApiResponses({@ApiResponse(code = 200,message = "OK",response = BaseResult.class),})
    @GetMapping("/redisSetTest/{setValue}")
    public BaseResult redistest(@PathVariable @NotBlank(message = "店铺内建id不能为空") Long setValue)
    {  
        /*
        String id = "f6a01cf361e84fcc946b8f309a58a06b";
        
        YxLiveAddressEntity oYxLiveAddressEntity = oYxLiveAddressMapper.selectById(id);
        if(null != oYxLiveAddressEntity)
        {
            Long time = oYxLiveAddressEntity.getLiveEndTime() - System.currentTimeMillis();
            String key = LiveShopConstant.LIVE_ADDRESS_REDISKEY_PREFIX.concat(id);
            oRedisManager.set(key,oYxLiveAddressEntity,time);
        }
        return BaseResult.success(oYxLiveAddressEntity);
        */
        String redisKey = "tmp_1a96df8b35ed4174a3558c7b10fbc963";
        //Long setValue = 200000000000000000L;
        oRedisManager.set(redisKey, setValue);        
        //Long valueTmp = (Long)oRedisManager.get(redisKey);
        return BaseResult.success(setValue);
    } 
    /*** 
    * 测试 redis Add Test
    * @param id
    * @param oYxLiveAppealDTO
    * @return BaseResult
    **/
    @ApiOperation(value ="测试redis Add Test",notes = "此接口用于redis Add Test测试")
    @ApiResponses({@ApiResponse(code = 200,message = "OK",response = BaseResult.class),})
    @GetMapping("/redisAddTest")
    public BaseResult redisAddTest()
    {  
        String redisKey = "tmp_1a96df8b35ed4174a3558c7b10fbc963";
        Long setValue = 20000L;
        oRedisManager.incrBy(redisKey, setValue);        
        Long getValue = Long.valueOf(oRedisManager.getT(redisKey));
        return BaseResult.success(getValue);
    }
     /*** 
    * 测试 redis Read Test
    * @param id
    * @param oYxLiveAppealDTO
    * @return BaseResult
    **/
    @ApiOperation(value ="测试redis Read Test",notes = "此接口用于redis Read Test测试")
    @ApiResponses({@ApiResponse(code = 200,message = "OK",response = BaseResult.class),})
    @GetMapping("/redisReadTest")
    public BaseResult redisReadTest()
    {  
        String redisKey = "tmp_1a96df8b35ed4174a3558c7b10fbc963";
        Long readValue = Long.valueOf(String.valueOf(oRedisManager.get(redisKey)));
        return BaseResult.success(readValue);
    } 
     /*** 
    * 测试 根据userId获取toekn
    * @param userId
    * @return BaseResult
    **/
    @ApiOperation(value ="测试根据userId获取toekn",notes = "此接口用于根据userId获取toekn")
    @ApiResponses({@ApiResponse(code = 200,message = "OK",response = BaseResult.class),})
    @GetMapping("/getTokenByUserId/{userId}")
    public BaseResult getTokenByUserId(@PathVariable @NotBlank(message = "userId不能为空") Long userId)
    {  
        YxSysUserEntity user = userMapper.selectOne(new LambdaQueryWrapper<YxSysUserEntity>()
                .eq(YxSysUserEntity::getUserId, userId)
                .eq(YxSysUserEntity::getStatus, CommonConstant.ONE)
        );
        LoginUserVo loginUserVo = getLoginUserVo(user);
        return BaseResult.success(loginUserVo);
    }
     /*** 
    * 测试 解析toekn信息
    * @param userId
    * @return BaseResult
    **/
    @ApiOperation(value ="解析toekn信息",notes = "此接口用于解析toekn信息")
    @ApiResponses({@ApiResponse(code = 200,message = "OK",response = BaseResult.class),})
    @GetMapping("/parsingToken")
    public BaseResult parsingToken(@RequestParam @NotBlank(message = "userId不能为空") String token)
    {  
        String JWT_TOKEN = "token!@#$yxw2023";
        StringBuilder StringMatter = new StringBuilder();
        DecodedJWT oDecodedJWT = null;//JWT.decode(token);
        try
        {
            oDecodedJWT = JWT.require(Algorithm.HMAC256(JWT_TOKEN)).build().verify(token);
        } 
        catch (Exception e) 
        {
            log.error("token认证失败,TokenUtil->getTokenInfoByToken  e.getMessage:{}", e.getMessage());
            return null;
        }
        Map<String, Claim> map = oDecodedJWT.getClaims();
        
        map.forEach((k,v)->{
            StringMatter.append(k);
            StringMatter.append("=");
            Claim claim = v;            
            StringMatter.append(claim.asString());
            StringMatter.append(";");
        });
        
        Claim oClaim = map.get("token");
        String tokenString = oClaim.asString();        
        JSONObject oJSONObject = (JSONObject)JSON.parse(tokenString);
        return BaseResult.success(StringMatter.toString());
    }    
    /*** 
    * 修改直播间封面
    * @param oYxLiveShopApplyDTO
    * @return BaseResult
    **/
    @ApiOperation(value ="修改直播间封面",notes = "修改直播间封面")
    @ApiResponses({@ApiResponse(code = 200,message = "OK",response = BaseResult.class),})
    @PostMapping("/uploadPictureTest")
    //@ApiImplicitParams({
    //        @ApiImplicitParam(paramType = "multipart/form-data", name = "defaultHomePicture", value = "缺省的直播间背景图片", required = true, dataType = "__file")
    //})
    public BaseResult uploadPictureTest()
    {
        String fileName = "D:\\file\\b1303fcaaa224a8fbfcbc60e5f37f505.jpg";
        File oFile = new File(fileName);
        String obsDownloadUrlStartPoint = huaWeiObsUtil.getObsDownloadUrlStartPointNoEndSlash();
        String liveHomePicture = "";         
        String fileNameInner = UUID.randomUUID().toString().replace("-", "") + oFile.getName().substring(oFile.getName().lastIndexOf(CommonConstant.POINT));
        String liveHomePictureKey = "images:" + fileNameInner;
        System.out.println("liveHomePictureKey:" + liveHomePictureKey);
        liveHomePicture = obsDownloadUrlStartPoint.concat("/").concat(liveHomePictureKey);
        /*
        if(liveHomePictureKey.startsWith("/"))
        {
            liveHomePicture = obsDownloadUrlStartPoint.concat(liveHomePictureKey);
        }
        else
        {
            liveHomePicture = obsDownloadUrlStartPoint.concat("/").concat(liveHomePictureKey);
        }
        */
        System.out.println("liveHomePicture：" + liveHomePicture);
        
        ObsClient oObsClient = huaWeiObsUtil.getObsClient();
        try
        {  
            String tmp = "images/" + fileNameInner;//new String(liveHomePictureKey.getBytes("UTF-8"),"UTF-8");
            PutObjectResult oPutObjectResult = huaWeiObsUtil.uploadFile(oObsClient,tmp, oFile);
            System.out.println("直播间图片oPutObjectResult.getStatusCode()：" + oPutObjectResult.getStatusCode());
        }
        catch (Exception e)
        {  
            try
            {  
                oObsClient.close();
            }
            catch (Exception ee)
            {              
                System.out.println("直播间图片上传，关闭客户端异常："+ee.getMessage());            
            } 
            System.out.println("直播间图片上传异常："+e.getMessage());
            throw new BaseException("直播间图片上传异常："+e.getMessage());
        }         
        try
        {  
            oObsClient.close();
        }
        catch (Exception ee)
        {              
            System.out.println("直播间图片传异常："+ee.getMessage());            
        }
       
        //System.out.println("defaultHomePicture.getOriginalFilename()：" + defaultHomePicture.getOriginalFilename());
        /*
        String obsDownloadUrlStartPoint = huaWeiObsUtil.getObsDownloadUrlStartPointNoEndSlash();
        String liveHomePicture = "";
        String liveHomePictureKey = FileClassifyEnum.LIVE_FILE.getPath() + BaseDateTime.getShortDateStringNoSlipt() + "/" + UUID.randomUUID().toString().replace("-", "") + defaultHomePicture.getOriginalFilename().substring(defaultHomePicture.getOriginalFilename().lastIndexOf(CommonConstant.POINT));
        System.out.println("liveHomePictureKey：" + liveHomePictureKey);
        if(liveHomePictureKey.startsWith("/"))
        {
            liveHomePicture = obsDownloadUrlStartPoint.concat(liveHomePictureKey);
        }
        else
        {
            liveHomePicture = obsDownloadUrlStartPoint.concat("/").concat(liveHomePictureKey);
        }
        System.out.println("liveHomePicture：" + liveHomePicture);
        //直播间图片上传华为云   
        ObsClient oObsClient = huaWeiObsUtil.getObsClient();
        try
        {  
            PutObjectResult oPutObjectResult = huaWeiObsUtil.uploadStreamNotClose(oObsClient,liveHomePictureKey, defaultHomePicture.getInputStream());
            System.out.println("直播间图片oPutObjectResult.getStatusCode()：" + oPutObjectResult.getStatusCode());
        }
        catch (Exception e)
        {  
            try
            {  
                oObsClient.close();
            }
            catch (Exception ee)
            {              
                System.out.println("直播间图片上传，关闭客户端异常："+ee.getMessage());            
            } 
            System.out.println("直播间图片上传异常："+e.getMessage());
            throw new BaseException("直播间图片上传异常："+e.getMessage());
        } 

        try
        {  
            oObsClient.close();
        }
        catch (Exception ee)
        {              
            System.out.println("直播间图片传异常："+ee.getMessage());            
        }           
        return BaseResult.success(liveHomePicture);
        */
        return BaseResult.success(liveHomePicture);
    }
    
    /**
     * 登录返回信息
     * @param user
     * @return
     */
    private LoginUserVo getLoginUserVo(YxSysUserEntity user) {
        LoginUserVo loginUserVo = new LoginUserVo();
        UserInfoVo userInfoVo = new UserInfoVo();
        BeanUtil.copyProperties(user, userInfoVo);
        long checkCode = System.currentTimeMillis();
        UserTokenVo userTokenVo = new UserTokenVo();
        userTokenVo.setId(user.getUserId());
        BeanUtil.copyProperties(user, userTokenVo);
        userTokenVo.setCheckCode(checkCode);
        userTokenVo.setExpirationDate(LocalDateTime.now().plusMinutes(30));
        userTokenVo.setMobilePhone(user.getPhone());
        String token = JwtUtil.generateToken(userTokenVo, checkCode);
        loginUserVo.setUser(userInfoVo);
        loginUserVo.setToken(token);
        return loginUserVo;
    } 
    
}
